package com.qixiucoding.strategy;

import com.qixiucoding.util.SpringContextUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.context.annotation.DependsOn;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 策略Bean的处理
 *
 * @Author longhj
 * @Date 2021/10/30 星期六 21:00
 */
@Component
@Slf4j
@DependsOn(value = "springContextUtil")
public class StrategyBeanContext {
    private final static Map<String, IStrategy> curMap = new ConcurrentHashMap<String, IStrategy>();

    public static Map<String, IStrategy> getBeanByInterface() {
        return SpringContextUtil.getBeanByInterface(IStrategy.class);
    }

    @PostConstruct
    private static void resolveStrategyBean() {
        Map<String, IStrategy> beanByInterface = getBeanByInterface();
        Iterator<Map.Entry<String, IStrategy>> iterator = beanByInterface.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry<String, IStrategy> next = iterator.next();
            IStrategy value = next.getValue();
            String key = next.getKey();
            StrategyName2 annotation = value.getClass().getAnnotation(StrategyName2.class);
            if (ObjectUtils.isEmpty(annotation)) {
                log.error("策略类：{}，没有注解策略名StrategyName",value.getClass().getName());
                continue;
            }
            String strategyName = annotation.strategyName();
            curMap.put(strategyName, value);
        }
    }

    public static Map<String, IStrategy> getStrategyBean() {
        return curMap;
    }
}
